#include "vg/image.h"
#include "seqbase/store.h"
#include "common.h"
#include "draw.h"

using namespace std;
using namespace anip;

class vg::Image::Renderer : public GraphicsRenderer
{
private:
	Image& _im;

public:
	Renderer(Image& s) :
		_im(s)
	{
		_version = s.version();
	}

	GraphicObject& graphicObject() const override { return _im; }
	void render(GraphicsRenderContext& cxt) override;
};

vg::Image::Image(vec2 pos, vec2 s):
	position(pos), size(s) {}

vg::Image::~Image()
{
	// decrease texture refcount
}

void vg::Image::Renderer::render(GraphicsRenderContext& cxt)
{
	if (!_im.texture) return;

	vec2 vpos = _im.position[_currentFrame];
	vec2 vsize = _im.size[_currentFrame];
	Draw::texture(vpos, vsize, _im.texture, _im.tint[_currentFrame]);

}

bool vg::Image::isInside(invec2 p, float time)
{
	vec2 pos = position[time];
	vec2 siz = size[time];

	vec2 d = p - pos;
	return d.x > 0 && d.y > 0 && d.x < siz.x&& d.y < siz.y;
}

GraphicsRenderer* vg::Image::createRenderer()
{
	return new Renderer(*this);
}

serializer_implementation(vg::Image)(Primitive& obj, ostream& out)
{
	auto& s = (Image&)obj;
	binaryWrite(s.position, out);
	binaryWrite(s.size, out);
	binaryWrite(s.tint, out);

	if (s.texture)
		binaryWrite(s.texture.object()->id(), out);
	else
		binaryWrite<int>(-1, out);
}

deserializer_implementation(vg::Image)(istream& in)
{
	auto s = new Image();
	binaryRead(s->position, in);
	binaryRead(s->size, in);
	binaryRead(s->tint, in);

	int id;
	binaryRead(id, in);
	if (id >= 0) s->texture.assign(&DataStore::getOrCreateFromId<STexture2D>(id));
	return s;
}